import { exec } from 'child_process';

async function restartService(serviceName: string): Promise<void> {
    try {
        console.log(`Stopping the service ${serviceName}...`);
        await executeCommand(`powershell.exe Stop-Service -Name "${serviceName}" -Force`);
        console.log(`The service ${serviceName} has been stopped.`);

        // Wait for a few seconds to ensure the service has time to stop.
        await new Promise(resolve => setTimeout(resolve, 5000));

        console.log(`Starting the service ${serviceName}...`);
        await executeCommand(`powershell.exe Start-Service -Name "${serviceName}"`);
        console.log(`The service ${serviceName} has been started.`);
    } catch (error) {
        console.error('Failed to restart the service:', error);
    }
}

function executeCommand(command: string): Promise<void> {
    return new Promise((resolve, reject) => {
        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.error(`Error executing command: ${stderr}`);
                return reject(error);
            }
            console.log(`Command output: ${stdout}`);
            resolve();
        });
    });
}

export default restartService;
